package at.ac.univie.zsu.aguataplan.util;

import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gerry
 * 
 */
public class Monitor {

	public static Rectangle calcPosition(Point p) {
		return calcPosition(p.x, p.y);
	}

	public static Rectangle calcPosition(int x, int y) {
		GraphicsEnvironment grapgicEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
		GraphicsDevice[] graphicDevices = grapgicEnvironment.getScreenDevices();

		List<Rectangle> monitors = new ArrayList<Rectangle>();

		Rectangle virtualBounds = new Rectangle();
		for (int j = 0; j < graphicDevices.length; j++) {
			GraphicsDevice grapgicDevice = graphicDevices[j];
			GraphicsConfiguration[] graphicConfigurations = grapgicDevice.getConfigurations();
			for (int i = 0; i < graphicConfigurations.length; i++) {
				virtualBounds = virtualBounds.union(graphicConfigurations[i].getBounds());
				monitors.add(graphicConfigurations[i].getBounds());
			}
		}

		for (Rectangle monitor : monitors) {
			if (insideScreen(x, y, monitor)) {
				return monitor;
			}
		}

		return new Rectangle(640, 480);

	}

	private static boolean insideScreen(int x, int y, Rectangle r) {
		int x1 = r.x;
		int x2 = r.x + r.width;
		int y1 = r.y;
		int y2 = r.y + r.height;

		if (x >= x1 && x < x2 && y >= y1 && y < y2) {
			return true;
		}

		return false;
	}
}
